package com.zhu.storesmanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.zhu.storesmanager.models.ModelItem;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.SalesData;
import com.zhu.storesmanager.views.DateView;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 销量上报查询界面
 */
public class SalesPutInquiryActivity extends Activity implements View.OnClickListener{

	private static final int DATE_DIALOG_ID = 1; //对话框ID
	private static long DAY = 1000 * 60 * 60 * 24;
	//异步查询数据库token
    private final static int MODEL_LIST_QUERY_TOKEN = 0; //查询所有型号 token 
    private DataQueryHandler mDataQueryHandler = null; //数据异步查询Handler

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	private TextView mTitleView = null; //标题栏
	private DateView mDateView = null; //日期栏
	private TextView mPutTimeView = null; //上传时间显示
	private LinearLayout mBodyView = null; //所有型号列表内容界面
	private List<ModelItem> mModelList = new ArrayList<ModelItem>(); //所有查询结果型号列表集合

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_salesputinquiry); //设置显示界面布局
		setupViews();
		initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupViews(){
		mTitleView = (TextView)findViewById(R.id.title_text);
		mBodyView = (LinearLayout)findViewById(R.id.list_body);
		findViewById(R.id.spi_bottom_back).setOnClickListener(this);
		findViewById(R.id.spi_search_button).setOnClickListener(this);
		mDateView = (DateView)findViewById(R.id.spi_date); //日期栏
		mDateView.initData(this, DateView.TYPE_DAY, 0);
		mPutTimeView = (TextView)findViewById(R.id.spi_date); //上传时间
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		mTitleView.setText(R.string.salesputinquiry);
		updateView(false); //默认无数据更新界面
		mDataQueryHandler = new DataQueryHandler(this.getContentResolver());
	}

	/**
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v != null){
			switch(v.getId()){
				case R.id.spi_bottom_back: //返回
					finish();
					break;
				case R.id.spi_search_button: //查询
					try{
						startQuery(mDateView.getTime());
					}catch(Exception e){
						e.printStackTrace();
					}
					break;
				case R.id.spi_date: //选择日期
					showDialog(DATE_DIALOG_ID);
					break;
			}
		}
	}

	/**
	 * 更具查询结果更新界面
	 * @param hasData 是否查询有数据
	 */
	private void updateView(boolean hasData){
		int visible = hasData ? View.VISIBLE : View.INVISIBLE;
		findViewById(R.id.spi_puttime).setVisibility(View.GONE); //显示或隐藏上报时间栏
		findViewById(R.id.spi_label).setVisibility(visible); //显示或隐藏型号标签栏
		mBodyView.setVisibility(visible); //显示或隐藏型号列表结果内容
	}

	/**
	 * 创建日期选择dialog
	 * @param id 创建dialogID
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	protected Dialog onCreateDialog(int id) {
		if(mDateView != null){
			return mDateView.onCreateDialog(id);
		}
		return null;
	}

	/**
	 * 准备dialog数据
	 * (non-Javadoc)
	 * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
	 */
	 @Override 
	 protected void onPrepareDialog(int id, Dialog dialog) { 
	    if(mDateView != null){
	    	mDateView.onPrepareDialog(id, dialog);
	    }
	 }

	/**
	 * 异步数据查询
	 */
	private final class DataQueryHandler extends AsyncQueryHandler {
		public DataQueryHandler(ContentResolver contentResolver) {
			super(contentResolver);
		}

		/**
		 * 查询结果返回 (non-Javadoc)
		 * 
		 * @see android.content.AsyncQueryHandler#onQueryComplete(int,
		 *      java.lang.Object, android.database.Cursor)
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			switch (token) {
			case MODEL_LIST_QUERY_TOKEN:
				updateModelListFromCursor(cursor);
				break;
			default:
				Log.e("zhu", "onQueryComplete called with unknown token "
						+ token);
			}
		}

		@Override
		protected void onDeleteComplete(int token, Object cookie, int result) {

		}
	}

	/**
	 * 更具查询结果更新型号列表
	 * @param cursor 查询结果数据
	 */
	private void updateModelListFromCursor(Cursor cursor){
		if(mModelList != null){
			mModelList.clear(); //清空数据
		}
		try {
            final int modelNameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.ReportedSalesColumns.MODELNAME);
            final int numIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.ReportedSalesColumns.SALESNUM);
            final int priceIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.ReportedSalesColumns.SALESPRICE);
            while (cursor.moveToNext()) {//遍历所有型号数据
            	ModelItem item = new ModelItem();
            	item.mName = cursor.getString(modelNameIndex);
            	item.mQuantity = cursor.getInt(numIndex);
            	item.mPrice = cursor.getInt(priceIndex);
            	mModelList.add(item); //加入数据集
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateModelListFromCursor error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
		updateView(true);
		updateBodyList();
	}

	/**
	 * 更新型号列表界面
	 */
	private void updateBodyList(){
		mBodyView.removeAllViews(); //清空数据
		for(int i = 0; i < mModelList.size(); i++){ //添加所有列表数据
			View view = getView(mModelList.get(i));
			mBodyView.addView(view);
		}
	}

	/**
     * 获取型号列表项界面
     * @param item 型号数据
     */
    private View getView(ModelItem item) {
        View view = LayoutInflater.from(this).inflate(R.layout.model_item, null);
        ((TextView)view.findViewById(R.id.model_name)).setText(item.mName);
        EditText edittext = (EditText)view.findViewById(R.id.model_text);
        EditText priceedittext = (EditText)view.findViewById(R.id.model_price);
        setEditText(edittext, item.mQuantity);
        setEditText(priceedittext, item.mPrice);
        return view;
    }

    /**
     * 设置输入框
     * @param editText 输入框
     * @param text 文本
     */
    private void setEditText(EditText editText, int text){
    	  if(text != Integer.MIN_VALUE){
    		  editText.setText("" + text);
          }
    	  editText.setTextColor(0xFF000000);
    	  editText.setFocusableInTouchMode(false);
    	  editText.setEnabled(false);
    	  editText.setFocusable(false);
    }

    /**
     * 更具时间查询列表
     * @param time 时间
     */
    private void startQuery(long time){
    	String where = StoresManagerSettings.ReportedSalesColumns.REPORTTIME + ">" + time  + " and " +
    			StoresManagerSettings.ReportedSalesColumns.REPORTTIME + "<" + (time +DAY) + " or " +
    			StoresManagerSettings.ReportedSalesColumns.REPORTTIME + "=" + time;
    	mDataQueryHandler.startQuery(MODEL_LIST_QUERY_TOKEN, null, StoresManagerSettings.ReportedSalesColumns.CONTENT_URI_NO_NOTIFICATION, 
    			null, where, null, null);
    }
}
